USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_list_reverse') BEGIN
	DROP  FUNCTION  tsql.fn_list_reverse
	PRINT '<<< DROP FUNCTION tsql.fn_list_reverse - Completed with SUCCESS >>>'
END
GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			tsql.fn_list_reverse
Type:			User defined function 
Owner:					
Description:	Reverses the elements of a  list similar to REVERSE()  
Parameters:		@list = list of numeric values comma delimited
Dependens on:  	fn_split
Usage:			SELECT [tsql].[fn_list_reverse] ('7,2,12,23,3,4,5')
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_list_reverse&referringTitle=Documentation		
Version:		20121024
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		10/24/2012 - Adrian E Dudau - Function created
================================================================================================*/

CREATE FUNCTION [tsql].[fn_list_reverse] (@list NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) 
AS

BEGIN /*FUNCTION*/
	DECLARE @Result NVARCHAR(MAX)
	DECLARE @item_value NVARCHAR(4000)

	SET @result = ''
	
	DECLARE curs CURSOR FOR 
	SELECT item_value 
	FROM [tsql].[fn_split](@list,',')
	ORDER BY id DESC 
	 
	OPEN curs
	FETCH NEXT FROM curs INTO @item_value

	WHILE @@FETCH_STATUS = 0 BEGIN
	SELECT  @result = @result + CASE WHEN @result = '' THEN '' ELSE ',' END + @item_value
	FETCH NEXT FROM curs INTO @item_value
	END

	CLOSE curs
	DEALLOCATE curs

	RETURN @Result END /*FUNCTION*/

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_list_reverse') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_list_reverse - Completed with SUCCESS >>>'
END

ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_list_reverse - Completed with ERROR >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------


